package priv.dajie.tzzq.common;

import priv.dajie.tzzq.bot.model.Fee;

import java.math.BigDecimal;

public class SteamPrice {
    public static BigDecimal feePrice(BigDecimal price){
        return feePrice(price.doubleValue());
    }

    public static BigDecimal feePrice(double price) {
        int priceInt = (int) (price * 100);
        int num = 0;
        int rprice = (int) (priceInt / 1.15);
        Fee feeInfo = calculate(rprice);
        boolean flag = false;
        while (feeInfo.getAmount() != priceInt && num < 10) {
            if (feeInfo.getAmount() > priceInt) {
                if (flag) {
                    feeInfo = calculate(rprice - 1);
                    feeInfo.setSteamFee(feeInfo.getSteamFee() + (priceInt - feeInfo.getAmount()));
                    feeInfo.setFee(feeInfo.getSteamFee() + (priceInt - feeInfo.getAmount()));
                    break;
                }
                else {
                    rprice -= 1;
                }
            } else {
                rprice += 1;
                flag = true;
            }
            feeInfo = calculate(rprice);
            num++;
        }
        double reInt = (priceInt - feeInfo.getFee());
        return new BigDecimal((reInt/100)+"");
    }

    private static Fee calculate(int price) {
        int steamFee = ((int) price * 0.05) > 1 ? (int) (price * 0.05) : 1;
        int publishFee = ((int) price * 0.1) > 1 ? (int) (price * 0.1) : 1;
        int amount = price + steamFee + publishFee;
        int fee = steamFee + publishFee;
        return new Fee(steamFee, publishFee, amount, fee);
    }
}
